import express from 'express';
import sqlite3 from 'sqlite3';
import { v4 as uuidv4 } from 'uuid';

const router = express.Router();
const db = new sqlite3.Database('./data/mirna.db');

// 绑定检测盒
router.post('/bind', (req, res) => {
  const { boxId, batchNumber, firmwareVersion } = req.body;
  
  const sql = `INSERT OR REPLACE INTO test_boxes (box_id, batch_number, firmware_version) VALUES (?, ?, ?)`;
  
  db.run(sql, [boxId, batchNumber, firmwareVersion], function(err) {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    res.json({ 
      success: true, 
      message: '检测盒绑定成功',
      boxId 
    });
  });
});

// 获取检测进度
router.get('/progress/:boxId', (req, res) => {
  const { boxId } = req.params;
  
  const sql = `SELECT * FROM test_results WHERE box_id = ? ORDER BY created_at DESC LIMIT 1`;
  
  db.get(sql, [boxId], (err, row) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    
    if (!row) {
      return res.json({ 
        status: 'waiting',
        progress: 0,
        message: '等待检测开始'
      });
    }
    
    const elapsed = Date.now() - new Date(row.created_at).getTime();
    const progress = Math.min(Math.floor((elapsed / (30 * 60 * 1000)) * 100), 100);
    
    res.json({
      status: row.result_status || 'processing',
      progress,
      result: row
    });
  });
});

// 提交检测结果
router.post('/result', (req, res) => {
  const { boxId, patientId, mir193a5pLevel, confidenceScore, analysisTime } = req.body;
  
  const sql = `INSERT INTO test_results (box_id, patient_id, mir_193a_5p_level, confidence_score, analysis_time, result_status) VALUES (?, ?, ?, ?, ?, ?)`;
  
  db.run(sql, [boxId, patientId, mir193a5pLevel, confidenceScore, analysisTime, 'completed'], function(err) {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    
    res.json({ 
      success: true, 
      message: '检测结果已保存',
      resultId: this.lastID 
    });
  });
});

// 获取检测报告
router.get('/report/:resultId', (req, res) => {
  const { resultId } = req.params;
  
  const sql = `SELECT tr.*, tb.batch_number, tb.firmware_version 
               FROM test_results tr 
               JOIN test_boxes tb ON tr.box_id = tb.box_id 
               WHERE tr.id = ?`;
  
  db.get(sql, [resultId], (err, row) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    
    if (!row) {
      return res.status(404).json({ error: '报告不存在' });
    }
    
    res.json({
      report: {
        patientId: row.patient_id,
        boxId: row.box_id,
        batchNumber: row.batch_number,
        mir193a5pLevel: row.mir_193a_5p_level,
        confidenceScore: row.confidence_score,
        analysisTime: row.analysis_time,
        testDate: row.created_at,
        clinicalAccuracy: '>95%',
        status: '正常'
      }
    });
  });
});

export default router;